package com.xxxx.manager.service.impl;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import com.xxxx.manager.service.UploadService;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
public class UploadServiceImpl implements UploadService {
    @Override
    public String upload(InputStream inputStream, String fileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "jpDrva9HDWmvnIOwBuRR5NZCTO7te9z0aIa10lak";
        String secretKey = "MehFgzxs48pOgk3O_rHsfkYB-RaBUxXSuDsilSmk";
        String bucket = "ego-demo";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
        String url = null;
        try {
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //返回url
                url = "http://qfyjg8t3n.hd-bkt.clouddn.com/"+fileName;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return url;
    }
}
